<?php

namespace App\Http\Middleware;

use Closure;
use GatewayWorker\Lib\Gateway;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class CheckUserToken extends Controller
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //token存在则取redis缓存数据
        if(isset(self::$request['token']) && !empty(self::$request['token'])) {
            self::$userToken = self::$request['token'];//设置userToken为全局
            self::$userData = self::getUserToken();//获取用户数据
            self::$userId = self::$userData['id'];//获取用户id
            self::bindUid(self::$userData['id']);//用户id绑定client_id
            self::bindUserData(self::$userData);//用户数据绑定client_id
        }else{//处于ping时的操作
            if(self::$client_id) {
                self::$userData = Gateway::getSession(self::$client_id);//通过client_id获取用户数据
                self::$userId = Gateway::getUidByClientId(self::$client_id);//通过client_id获取用户id
            }
        }

        if(!self::$userData) {//处于token失效或者token错误的时候触发
            return response()->json([],404);
        }else{//用户数据已存储可通过全局参数获取用户的所有信息
            return $next($request);
        }
    }
}
